package study.算法Algorithm.常用10种算法.普利姆算法;

import java.util.Arrays;

public class PrimAlgorithm {

    public static void main(String[] args) {
        char[] data = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        int verxs = data.length;
        //邻接矩阵的关系使用二维数组表示  ，10000表示两个点不连通
        int[][] weight = new int[][]{
                {10000, 5, 7, 10000, 10000, 10000, 2},
                {5, 10000, 10000, 9, 10000, 10000, 3},
                {7, 10000, 10000, 10000, 8, 10000, 10000},
                {10000, 9, 10000, 10000, 10000, 4, 10000},
                {10000, 10000, 8, 10000, 10000, 5, 4},
                {10000, 10000, 10000, 4, 5, 10000, 6},
                {2, 3, 10000, 10000, 4, 6, 10000},};

        Graph graph = new Graph(verxs);
        MinTree minTree = new MinTree();
        minTree.createGraph(graph, verxs, data, weight);
        minTree.showGraph(graph);
        //测试普利姆算法
        minTree.prim(graph, 0);
    }
}

//创建最小生成树
class MinTree {

    public void createGraph(Graph graph, int verxs, char data[], int[][] weight) {
        int i, j;
        for (i = 0; i < graph.verxs; i++) {
            graph.data[i] = data[i];
            for (j = 0; j < verxs; j++) {
                graph.weight[i][j] = weight[i][j];
            }
        }
    }

    //显示图的邻接矩阵
    public void showGraph(Graph graph) {
        for (int[] link : graph.weight) {
            System.out.println(Arrays.toString(link));
        }
    }

    //编写prim算法得到最小生成树

    /**
     * @param graph 图
     * @param v     表示从图的第几个顶点开始生成
     */
    public void prim(Graph graph, int v) {
        int sum = 0;
        //用来标记  顶点是否被访问过
        int[] visited = new int[graph.verxs];

        //把当前节点标记为已访问
        visited[v] = 1;
        //h1和h2  记录两个顶点的下标
        int h1 = -1;
        int h2 = -1;
        int miniWeight = 10000;  //将miniWeight 初始化成一个大值，后面再遍历过程中，会被替换
        for (int k = 1; k < graph.verxs; k++) {  //生成 定点数-1条边
            for (int i = 0; i < graph.verxs; i++) {
                for (int j = 0; j < graph.verxs; j++) {
                    if (visited[i] == 1 && visited[j] == 0 && graph.weight[i][j] < miniWeight) {
                        //替换miniWeight
                        miniWeight = graph.weight[i][j];
                        h1 = i;
                        h2 = j;
                    }
                }
            }
            sum += miniWeight;
            System.out.println("边<" + graph.data[h1] + "," + graph.data[h2] + ">权值：" + miniWeight);
            //将当前这个节点标记为已经访问
            visited[h2] = 1;
            //重置miniWeight
            miniWeight = 10000;
        }
        System.out.println("最短路径为：" + sum);
    }
}

class Graph {
    int verxs;  //表示图的节点个数
    char[] data;  //存放节点数据
    int[][] weight;  //存放边   邻接矩阵

    public Graph(int verxs) {
        this.verxs = verxs;
        data = new char[verxs];
        weight = new int[verxs][verxs];
    }
}
